package com.org.daniel.framework.shiro;

import com.org.daniel.module.entity.manager.ManagerUser;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * @author Daniel
 */
public class PasswordHelper {

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	public static final String ALGORITHM_NAME = "md5"; // 基础散列算法
	public static final int HASH_ITERATIONS = 2; // 自定义散列次数

	public void encryptPassword(ManagerUser managerUser){
		// 随机字符串作为salt因子，实际参与运算的salt还引入其他干扰因子
		String salt = randomNumberGenerator.nextBytes().toHex();
		managerUser.setSalt(salt);
		String newPassword = new SimpleHash(ALGORITHM_NAME, managerUser.getPassword(), ByteSource.Util.bytes(salt), HASH_ITERATIONS).toHex();
		managerUser.setPassword(newPassword);
	}

	public static void main(String[] argv){
		RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
		String salt = randomNumberGenerator.nextBytes().toHex();
		System.out.println("salt=["+salt+"]");
		String newPassword = new SimpleHash(ALGORITHM_NAME, "admin123", ByteSource.Util.bytes(salt), HASH_ITERATIONS).toHex();
		System.out.println("password=["+newPassword+"]");
	}

}
